﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MTQ.Web.Controllers
{
    public class AccountAuthAttribute : AuthorizeAttribute
    {
        // 只需重载此方法，模拟自定义的角色授权机制   
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //string currentRole = GetRole(httpContext.User.Identity.Name);              
            //if(Roles.Contains(currentRole ) )   
            //return true;  

            //object listUserAction = httpContext.Session["listUserAction"];
            //if (listUserAction == null)
            //{
            //    httpContext.Response.Redirect("/Login/Index");
            //    httpContext.Response.StatusCode = 401;
            //    return false;
            //}
            object listUserAction = httpContext.Session["UserInfo"]; 
            if (listUserAction == null) {
                httpContext.Response.Redirect("/Login/Index");
                //    httpContext.Response.StatusCode = 401;
                return false;
            }

            var userInfo = listUserAction as MTQ.Model.Base_UserInfo;

            System.Threading.Tasks.Task.Run<bool>(() =>
            {
                var t1 = System.Threading.Tasks.Task.Run(() =>
                {
                    BLL.Log_WebService.SaveRequestLog(httpContext.Request, userInfo.User_UserName);
                });
                return true;
            });

            return true;

            //if (GetUserPower(listUserAction, Roles))
            //{
            //    return true;
            //}
            //httpContext.Response.StatusCode = 401;
            ////httpContext.Response.StatusCode = 403;//无权限状态码  
            //return false;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //string path = filterContext.HttpContext.Request.Path;            
            //const string strUrl = "/Home/page403";
            //filterContext.HttpContext.Response.Redirect(string.Format(strUrl, HttpUtility.UrlEncode(path)), true);

            base.HandleUnauthorizedRequest(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 401)
            {
                filterContext.Result = new RedirectResult("/Home/page403");
            }
        }

        /// <summary>
        /// 判断Action是否在该用户的权限内
        /// </summary>
        /// <param name="actionName"></param>
        /// <returns></returns>
        private bool GetUserPower(object objUserAction, string actionName)
        {
            List<string> lstUserAction = objUserAction as List<string>;
            bool Exist = lstUserAction.Contains(actionName) ? true : false;
            return Exist;
        }


    }
}